package cn.js189.common.util;

import cn.js189.common.util.helper.UUIDHelper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.util.Objects;

@Slf4j
public class Base64Util {
	
	// 对字节数组字符串进行Base64解码生成文件
	public static File generateFile(String base64Str, String fileName) {
		if (base64Str == null) {
			return null;
		}
		BASE64Decoder decoder = new BASE64Decoder();
		String uuid = UUIDHelper.getUUID();
		// 文件夹路径
		String path = Objects.requireNonNull(Base64Util.class.getClassLoader().getResource("/")).getPath() + "mailFiles/" + uuid + "/";
		// 文件路径
		log.debug("文件夹路径：{}",path);
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		String mailPath = path + fileName;
		log.debug("邮件附件路径: " + mailPath);
		try(FileOutputStream out = new FileOutputStream(mailPath)) {
			//Base64解码
			byte[] b = decoder.decodeBuffer(base64Str);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					//调整异常数据
					b[i] += (byte) 256;
				}
			}
			out.write(b);
			return new File(mailPath);
		} catch (Exception e) {
			return null;
		}finally{
			log.debug("关闭流");
		}
	}
	
	public static File[] getFile(String files) {
		if (StringUtils.isEmpty(files)) {
			return new File[0];
		}
		
		JSONArray array = JSON.parseArray(files);
		if (null == array || array.isEmpty()) {
			return new File[0];
		}
		
		File[] fileArr = new File[array.size()];
		for (int i = 0; i < array.size(); i++) {
			JSONObject fileObj = array.getJSONObject(i);
			String fileName = fileObj.getString("fileName");
			String base64Str = fileObj.getString("base64Str");
			File file = generateFile(base64Str, fileName);
			if (null != file && file.length() > 0) {
				fileArr[i] = file;
				log.debug("---获取文件:" + file.getName());
			}
		}
		return fileArr;
	}
	
	public String getPath(){
		return Objects.requireNonNull(this.getClass().getClassLoader().getResource("/")).getPath().replace("classes","mailFiles");
	}
	
	
	/**
	 * 将base64解码,并写入指定位置 对字节数组字符串进行Base64解码并生成文件
	 * @param base64   文件的bas464编码
	 * @param path      文件的保存路径
	 */
	public static boolean base64ToFile(String base64, String path) throws IOException {
		try {
			OutputStream out = new FileOutputStream(path);
			return base64ToOutput(base64, out);
		} catch (FileNotFoundException e) {
			log.error("Base64解码并写文件到指定位置异常:", e);
		}
		return false;
	}
	
	/**
	 * 处理Base64解码并输出流
	 * @param base64  文件的bas464编码
	 * @param out     输出流
	 */
	public static boolean base64ToOutput(String base64, OutputStream out) throws IOException {
		if (base64 == null) { // 图像数据为空
			return false;
		}
		try {
			// Base64解码
			byte[] bytes = Base64.decodeBase64(base64.getBytes());
			for (int i = 0; i < bytes.length; ++i) {
				if (bytes[i] < 0) {// 调整异常数据
					bytes[i] += (byte) 256;
				}
			}
			// 生成jpeg图片
			out.write(bytes);
			out.flush();
			return true;
		} finally {
			try {
				out.close();
			} catch (IOException e) {
				log.error("处理Base64解码并输出流异常:{}", e.getMessage(),e);
			}
		}
	}

}
